<template>
  <div>
     <table-title title="课程信息"></table-title> 
     <div class="course_data">
         <div class="course_left">
           <el-form label-width="100px" ref="courseForm" :model="formState" :rules="rules">
            <el-form-item label="课程名称" prop="Cname">
              <el-input v-model="formState.Cname"></el-input> <span>60字以内</span>
            </el-form-item>
             <el-form-item label="课程描述" prop="Cdescribe">
              <el-input v-model="formState.Cdescribe"></el-input > <span>100字以内</span>
            </el-form-item>
             <el-form-item label="课程价格" prop="Cprice">
              <el-input v-model="formState.Cprice"></el-input> <span>元为单位，免费设置为0</span>
            </el-form-item>
            <el-row style="display: flex;">
              <el-col :span="3" style="color:white;">专业选择：</el-col>
              <el-col :span="7" >
                  <el-form-item prop="CategoryOne">
                 <el-select  v-model="formState.CategoryOne">
                  <el-option v-for="item in opt1" :key="item.value"
                  :label="item.label" :value="item.value"></el-option>
                    </el-select>
               </el-form-item>
              </el-col>
              <el-col :span="7">
                    <el-form-item prop="CategoryTwo">
                 <el-select  v-model="formState.CategoryTwo">
                  <el-option v-for="item in opt2"  :key="item.value"
                  :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>

              </el-col>
              <el-col :span="7">
                  <el-form-item prop="CategoryThree">
                 <el-select  v-model="formState.CategoryThree">
                  <el-option v-for="item in opt3" :key="item.value"
                  :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              </el-col>
            </el-row>
          
            <el-form-item>
              <el-button v-if="!$route.query.status" type="success" @click="toSave">保存</el-button>
            </el-form-item>
           </el-form>

         </div>
         <div class="course_right">
              <div class="course_img"> 
                <h3>课程封面</h3>
                <div class="img_wrap">
                  <img :src="'http://127.0.0.1:3000'+formState.Cpic" alt="">
                </div>
                <div class="img_btn">
                      <el-link type="danger">取消</el-link>
                      <el-link type="primary" @click="open">上传</el-link>
                </div>
              </div> 

          </div>
     </div>
     <el-dialog title="选择图片" v-model="imgFlag">
          <el-upload
            class="avatar-uploader"
            action="/VueHandler/VueHandler/UpLoadPicHandler"
            ref="myupLoad"
            :auto-upload="false"
            :on-change="fileChange"
            :on-success="getFile"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <template #footer v-if="imageUrl">
            <div>
                     <el-button type="primary" @click="closeImg">取消</el-button>
                    <el-button type="success" @click="toSubmit">确定</el-button>
            </div>
          </template>
     </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref,reactive,toRefs,defineEmits} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type {UploadFiles} from 'element-plus'
import CateHook from '../../../utils/cate'
import {addCourseApi,getCourse,saveAllcourse} from '../../../api/course'
import { ElMessage } from 'element-plus'
import {useRouter,useRoute} from 'vue-router'
import mitt from '../../../utils/mitt'
let router=useRouter()
let {query}=useRoute()
let emit=defineEmits(["sendFlag"])
let formState:any=reactive({
       _id:"",
      Cname:"",
      Cdescribe:"",
      Cprice:"",
      CategoryOne:"",
      CategoryTwo:"",
      CategoryThree:"",
      Cpic:"",
      Cdetails:"" //富文本的内容
})
// 监听兄弟组件 点击了整体保存
mitt.on('sendEditor',async (editorHtml:any)=>{
    formState.Cdetails=editorHtml;
    formState._id=query._id;//课程_id
   let res=await  saveAllcourse(formState)
   console.log(res,"------整体保存-----")
   router.push({
      name:"courselist"
   })
})
let rules={
     Cname:[{required:true,message:"名称必填",trigger:'blur'}],
   Cdescribe:[{required:true,message:"描述必填",trigger:'blur'}],
    Cprice:[{required:true,message:"价格必填",trigger:'blur'}],
     CategoryOne:[{required:true,message:"一级分类必填",trigger:'blur'}],
   CategoryTwo:[{required:true,message:"二级分类必填",trigger:'blur'}],
   CategoryThree:[{required:true,message:"三级分类必填",trigger:'blur'}]
}
let cate=CateHook() //从封装的hook中 获取的一二三级分类数据
let {opt1,opt2,opt3}=toRefs(cate)
console.log(opt1,"8888888888")
const imageUrl = ref('') //选择的图片
let imgFlag=ref(false)
let courseInfo=ref({})
let dirList=ref({})

let getCourseInfo=()=>{
      getCourse(query.ID).then(res=>{
                console.log(res,"7777777")
                courseInfo.value=res.data.courselist;
                dirList.value=res.data.dirlist
                let {Cname,Cprice,Cdescribe,Cpic,CategoryOne,CategoryTwo,CategoryThree,Cdetails}=res.data.courselist
                formState.Cname=Cname;
                formState.Cprice=Cprice;
                formState.Cdescribe=Cdescribe;
                    formState.CategoryOne=CategoryOne;
                    formState.CategoryThree=CategoryThree;
                    formState.CategoryTwo=CategoryTwo;
                    formState.Cpic=Cpic;
                    // 像兄弟组件传递回显目录列表数据
                    mitt.emit("senddir", dirList.value)
                      // 像兄弟组件富文本内容进行回显
                    mitt.emit("sendHtml", Cdetails)
            })
}
  // 监听兄弟组件删除目录
    mitt.on('getdir',()=>{
      console.log("监听删除目录了")
          getCourseInfo()
    })
// 判断地址栏中 是否有ID  如果 有ID 调用接口做回显
  if(query.ID){
      // 像父组件传递个flag 调整遮罩
     emit("sendFlag",true)
      getCourseInfo()
     
  }

if(query.status=="edit"){
    emit("sendFlag",false,"edit")
}


// 
let open=()=>{
  imgFlag.value=true;
}
// 文件选择
let fileChange=(uploadFile:any,uploadFiles: UploadFiles)=>{
    console.log(uploadFile,uploadFiles,"---------")
    // 制作缩略图
    let url=URL.createObjectURL(uploadFile.raw)
    console.log(url,"-----------")
    imageUrl.value=url;
}

// 点击确定触发上传
let myupLoad=ref()
let toSubmit=()=>{
  myupLoad.value.submit(); //手动触发了插件的上传方法
}

// 上传成功的回调
let getFile=(res:any)=>{
  console.log(res,"0000000000000")
  formState.Cpic=res.cacheName;//存储返回的课程封面
   imgFlag.value=false;
   imageUrl.value=''
}
  let closeImg=()=>{
    imgFlag.value=false;
  }
  let courseForm:any=ref()
  //添加课程接口
  let toSave= ()=>{
    courseForm.value.validate(async (vali:any)=>{
        if(vali){
          if(formState.Cpic){
              let res:any=await addCourseApi(formState)
              console.log(res)
                  ElMessage({
                  type:"success",
                  message:"课程添加成功"
                })
                // 跳转原页面 将ID 放置到地址栏
                router.push({
                  path:"/layout/courseadd",
                  query:{
                    ID:res.ID, //课程ID
                    _id:res._id //课程_id
                  }
                })
                // 像父组件传递个flag 调整遮罩
                  emit("sendFlag",true)


          }else{
              ElMessage({
                type:"error",
                message:"请先上传课程封面"
              })
          }
       
        }
    })
     
  }
</script>
<style lang="less" scoped>
  .course_data{
    display:flex;
    // background: #6c6c8f;
    margin-top: 20px;
   height:400px;
    .course_left{
      width:60%;
      height:400px;

    }
    .course_right{
      width:35%;
      margin-left:5%;
      height:400px;
    }
     ::v-deep .el-form-item{
      color:white;
     display: flex;
     .el-select{
       width: 220px;
       margin-left: 5px;
     }
     .el-input{
      width:400px;
      margin-right: 30px;
     }
    }
    ::v-deep .el-form-item__content{
        display: flex;
    }
    ::v-deep .el-form-item__label{
        color:white;
    }
  }
  .course_img{
    width: 254px;
    height: 300px;
    h3{
      color: white;
    }
    .img_wrap{
        width: 254px;
        height: 250px;
        border:1px solid white;
        img{
            width: 254px;
           height: 250px;
        }
    }
    .img_btn{
      display: flex;
        width: 254px;
      justify-content: space-between;
    }
  }
  .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
